# -*- coding: utf-8 -*-

"""
@project : TeleAI
@FileName: config_util
@Desc  : 
"""
import configparser

class MyConfigParser(configparser.ConfigParser):
    def __init__(self, defaults=None):
        configparser.ConfigParser.__init__(self, defaults=defaults)

    def optionxform(self, optionstr):
        return optionstr



class ConfigUtil(object):
    def __init__(self, config_path):

        self.config = MyConfigParser()
        self.config_path = config_path

        try:
            self.config.read(self.config_path, encoding="utf-8")
        except:
            # ailog.error('fail to read config ...')
            # ailog.save_error_log(job_id=0,job_type=-1,error_code='900006',key_word='配置文件读取失败')
            pass

    def read_config(self):
        self.config.read(self.config_path, encoding="utf-8")

    def to_dict(self):

        all_dict = dict()
        for sec in self.config.sections():
            sec_conf_dict = dict()
            for k, v in self.config.items(section=sec):
                sec_conf_dict[k] = v
            all_dict[sec] = sec_conf_dict

        return all_dict

    def get(self, section, option):
        try:
            res = self.config.get(section=section, option=option)
        except Exception as e:
            # ailog.error('不存在的配置 ：{} - {} '.format(section,option))
            # ailog.error('配置项读取错误 ： {}'.format(e))
            res = None

        return res

    def get_dict_by_section(self, section):
        sec_conf_dict = dict()
        for k, v in self.config.items(section=section):
            sec_conf_dict[k] = v
        return sec_conf_dict

    def change_conf(self,config_path, conf_Dict):
        config = MyConfigParser()
        config.read(config_path, encoding="utf-8")
        for key1, value1 in conf_Dict.items():
            for key2, value2 in value1.items():
                config.set(key1, key2, value2)
        config.write(open(config_path, "w", encoding="utf-8"))
